#include "gofgame/common/WeakRefTarget.h"

using namespace gofgame::common;

__WeakRefTarget::__WeakRefTarget() {
	this->refData = nullptr;
}

__WeakRefTarget::~__WeakRefTarget() {
	WeakRefData *refData = this->refData;
	if (refData) {
		refData->target = nullptr;
	}
}

void *__WeakRefTarget::__getOwner() const {
	__WeakRefTarget *this_ = const_cast<__WeakRefTarget*>(this);
	return reinterpret_cast<char*>(this_) - this->__addressOffset();
}

/* static */ void *__WeakRefTarget::__allocRefData(__WeakRefTarget *target) {
	if (target == nullptr) {
		return nullptr;
	}
	WeakRefData *refData = target->refData;
	if (refData) {
		refData->refCount++;
	} else {
		refData = new WeakRefData();
		refData->target = target;
		refData->refCount = 1;
		target->refData = refData;
	}
	return refData;
}

/* static */ void __WeakRefTarget::__deallocRefData(void *refData) {
	if (!refData) {
		return;
	}
	WeakRefData *refData2 = (WeakRefData*)refData;
	if (--refData2->refCount == 0) {
		if (refData2->target) {
			refData2->target->refData = nullptr;
		}
		delete refData;
	}
}